package com.fosss.tree;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

/**
 * 赫夫曼树
 * @author fosss
 */
public class HuffmanTree {
    public static void main(String[] args) {
        int[] arr = {13, 7, 8, 3, 29, 6, 1};
        Node root = createHuffmanTree(arr);
        preOrder(root);
    }

    /**
     * 创建赫夫曼树
     */
    public static Node createHuffmanTree(int[] arr) {
        List<Node> list = new ArrayList<>();
        //将数组中的每个数据都转化为结点，并纯出道集合中
        for (int i : arr) {
            list.add(new Node(i));
        }

        while (list.size() > 1) {
            //排序
            Collections.sort(list);

            //取前两个数据分别作为左右结点，和作为父节点
            Node leftNode = list.get(0);
            Node rightNode = list.get(1);
            Node parent = new Node(leftNode.value + rightNode.value);

            parent.left = leftNode;
            parent.right = rightNode;

            //将已经取出的数据从集合中排除掉
            list.remove(leftNode);
            list.remove(rightNode);

            //将parent添加到集合中
            list.add(parent);

        }
        return list.get(0);
    }

    /**
     * 前序遍历
     *
     * @param root 根结点
     */
    public static void preOrder(Node root) {
        if (root == null) {
            System.out.println("空！！！！！");
        } else {
            root.preOrder();
        }
    }
}

/**
 * 创建结点类
 */
class Node implements Comparable<Node> {
    /**
     * 存储值
     */
    public int value;
    /**
     * 左节点
     */
    public Node left;
    /**
     * 右节点
     */
    public Node right;

    public Node(int value) {
        this.value = value;
    }

    @Override
    public String toString() {
        return "Node{" +
                "value=" + value +
                '}';
    }

    /**
     * 从小到大排序
     *
     * @param o
     * @return
     */
    @Override
    public int compareTo(Node o) {
        return this.value - o.value;
    }

    /**
     * 前序遍历
     */
    public void preOrder() {
        System.out.println(this);
        if (this.left != null) {
            this.left.preOrder();
        }
        if (this.right != null) {
            this.right.preOrder();
        }
    }
}
























